import wafer from './wafer';
const ref = require('ref-napi');
const { BSON } = require('bson');

let waferDll = null;

export function initRingBuffer(
  capacity: number = 1024,
  dllPath?: string,
  dllName?: string,
) {
  waferDll = wafer(dllPath,dllName);
  return waferDll.initDataTransmission(capacity);
}

export function writeToRingBuffer(funcName: string, fno: number, msg: any) {
  const bsonMsg = BSON.serialize(msg);
  waferDll.writeDataTransmissionSw(bsonMsg, bsonMsg.length, funcName, fno);
}

export function readFromRingBuffer(bufferSize: number = 1024) {
  const buffer = Buffer.alloc(bufferSize);
  const outFuncName = Buffer.alloc(50);
  const outSize = ref.alloc('size_t');
  const fno = ref.alloc('size_t');
  const readResult = waferDll.readDataTransmissionSw(
    buffer,
    bufferSize,
    outSize,
    outFuncName,
    fno,
  );
  if (readResult !== 0) return null;
  const bsonBuffer = buffer.subarray(0, outSize.deref());
  const msg = BSON.deserialize(bsonBuffer);
  let zeroIndex = outFuncName.indexOf(0);
  const funcName = outFuncName.toString('utf8', 0, zeroIndex);
  return {
    funcName,
    data: msg,
    fno: fno.deref(),
  };
}

export function clearRingBuffer() {
  waferDll.clearAllDataTransmission();
}
